package com.applink.sell_proof.fragment;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;
import com.applink.sell_proof.QuizDetail;
import com.applink.sell_proof.R;
import com.applink.sell_proof.constant.Constant;
import com.applink.sell_proof.database.table.QuestionDBHelper;
import com.applink.sell_proof.database.table.QuizDBHelper;
import com.applink.sell_proof.model.Answer;
import com.applink.sell_proof.model.Question;

public class QuestionFragment extends SherlockFragment implements
		OnClickListener, OnCheckedChangeListener, OnTouchListener {
	private ViewGroup mLayout;
	protected GestureDetector mGestureDetector;

	public static QuestionFragment newInstance(long questionId) {
		QuestionFragment f = new QuestionFragment();
		Bundle args = new Bundle();
		args.putLong(Constant.QUESTION_ID, questionId);
		f.setArguments(args);

		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mGestureDetector = new GestureDetector(getActivity(),
				new GestureDetector.SimpleOnGestureListener() {
					private static final int SWIPE_THRESHOLD = 100;
					private static final int SWIPE_VELOCITY_THRESHOLD = 100;

					@Override
					public boolean onDown(MotionEvent e) {
						return true;
					}

					@Override
					public boolean onFling(MotionEvent e1, MotionEvent e2,
							float velocityX, float velocityY) {
						boolean result = false;
						try {
							float diffY = e2.getY() - e1.getY();
							float diffX = e2.getX() - e1.getX();
							if (Math.abs(diffX) > Math.abs(diffY)) {
								if (Math.abs(diffX) > SWIPE_THRESHOLD
										&& Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
									if (diffX > 0) {
										onSwipeRight();
										result = true;
									} else {
										onSwipeLeft();
										result = true;
									}
								}
							} else {
								if (Math.abs(diffY) > SWIPE_THRESHOLD
										&& Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
									if (diffY > 0) {
										// swipe bottom
									} else {
										// swipe top
									}
								}
							}
						} catch (Exception exception) {
							exception.printStackTrace();
						}
						return result;
					}
				});
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (mLayout == null) {
			mLayout = (ViewGroup) inflater.inflate(R.layout.question, null,
					false);
		}
		mLayout.findViewById(R.id.next_button).setOnClickListener(this);
		mLayout.findViewById(R.id.back_button).setOnClickListener(this);
		mLayout.findViewById(R.id.question_container).setOnTouchListener(this);
		if (((QuizDetail) getActivity()).isFirstPager()) {
			mLayout.findViewById(R.id.back_button)
					.setVisibility(View.INVISIBLE);
		}
		if (((QuizDetail) getActivity()).isLastPager()) {
			((TextView) mLayout.findViewById(R.id.next_button))
					.setBackgroundResource(R.drawable.btn_submit);
		} else {
			((TextView) mLayout.findViewById(R.id.next_button))
					.setBackgroundResource(R.drawable.btn_next);

		}
		long questionId = getArguments().getLong(Constant.QUESTION_ID);
		Question question = QuestionDBHelper.getQuestion(questionId,
				((QuizDetail) getActivity()).getQuiizId());
		if (question != null) {
			((TextView) mLayout.findViewById(R.id.question_content))
					.setText(question.getContent());
			for (Answer answer : question.getAnswers()) {
				if (answer.getType().equals(Answer.TEXT_ANSWER)) {
					buildTextAnswer(answer);
				} else if (answer.getType().equals(Answer.SINGLE_ANSWER)) {
					buildSingleAnswer(answer);
				} else if (answer.getType().equals(Answer.MULT_ANSWER)) {
					buildMultAnswer(answer);
				}
			}
		}
		return mLayout;
	}

	protected void buildTextAnswer(Answer textAnswer) {
		LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		EditText editText = new EditText(getActivity());
		editText.setLayoutParams(layoutParam);
		editText.setTextColor(getResources().getColor(R.color.black));
		editText.setBackgroundResource(R.drawable.textfield_hoto_light);
		final long answerId = textAnswer.getId();
		editText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				QuestionDBHelper.updateUserReply(answerId, s.toString());
			}
		});
		editText.setTag(textAnswer.getId());
		((ViewGroup) mLayout.findViewById(R.id.question_container))
				.addView(editText);
		if (textAnswer.getUserReply() != null) {
			editText.setText(textAnswer.getUserReply());
		}
	}

	protected void buildSingleAnswer(Answer singleAnswer) {
		RadioGroup radioGroup = new RadioGroup(getActivity());
		radioGroup.setOnCheckedChangeListener(this);
		radioGroup.setTag(singleAnswer.getId());
		LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		try {
			JSONObject jsonOption = new JSONObject(singleAnswer.getOptions());
			JSONArray arrayOption = jsonOption.getJSONArray("Option");
			for (int i = 0; i < arrayOption.length(); i++) {
				String option = arrayOption.getString(i);
				RadioButton radioOption = new RadioButton(getActivity());
				radioOption.setOnTouchListener(this);
				radioOption.setButtonDrawable(R.drawable.btn_radio_holo);
				radioOption.setText(option);
				radioOption.setTextColor(getResources().getColor(R.color.blue));
				RadioGroup.LayoutParams radioGroupLayoutParam = new RadioGroup.LayoutParams(
						RadioGroup.LayoutParams.MATCH_PARENT,
						RadioGroup.LayoutParams.WRAP_CONTENT);
				radioOption.setLayoutParams(radioGroupLayoutParam);
				radioGroup.addView(radioOption);
				if (singleAnswer.getUserReply().equals(option))
					radioOption.setChecked(true);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		radioGroup.setLayoutParams(layoutParam);
		((ViewGroup) mLayout.findViewById(R.id.question_container))
				.addView(radioGroup);
	}

	protected void buildMultAnswer(Answer muiltAnswer) {
		final long answerId = muiltAnswer.getId();
		LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		try {
			JSONObject jsonOption = new JSONObject(muiltAnswer.getOptions());
			JSONArray arrayOption = jsonOption.getJSONArray("Option");
			for (int i = 0; i < arrayOption.length(); i++) {
				String option = arrayOption.getString(i);
				CheckBox checkOption = new CheckBox(getActivity());
				checkOption.setOnTouchListener(this);
				checkOption.setText(option);
				checkOption.setChecked(muiltAnswer.getUserReply().contains(
						option));
				checkOption.setTag(muiltAnswer);
				checkOption.setTextColor(getResources().getColor(R.color.blue));
				checkOption.setLayoutParams(layoutParam);
				((ViewGroup) mLayout.findViewById(R.id.question_container))
						.addView(checkOption);
				checkOption
						.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
							@Override
							public void onCheckedChanged(
									CompoundButton buttonView, boolean isChecked) {
								try {
									ViewGroup parent = (ViewGroup) buttonView
											.getParent();
									List<String> replies = new ArrayList<String>();
									for (int i = 0; i < parent.getChildCount(); i++) {
										View checkbox = parent.getChildAt(i);
										if (CompoundButton.class
												.isInstance(checkbox)) {

											if (((CompoundButton) checkbox)
													.isChecked())
												replies.add(((CompoundButton) checkbox)
														.getText().toString());
										}
									}
									JSONArray arrayReply = new JSONArray(
											replies);
									JSONObject objectReply = new JSONObject();
									objectReply.put("Option", arrayReply);
									QuestionDBHelper.updateUserReply(answerId,
											objectReply.toString());
								} catch (JSONException e) {
									Log.e("TAG", e.toString());
								}
							}
						});
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back_button:
			((QuizDetail) getActivity()).backQuestion();
			break;
		case R.id.next_button:
			if (((QuizDetail) getActivity()).isLastPager()) {
				// reply quiz
				((QuizDetail) getActivity()).replyQuiz();
				QuizDBHelper.updateSubmitted(
						((QuizDetail) getActivity()).getQuiizId(), true);
			} else {
				// next question
				((QuizDetail) getActivity()).nextQuestion();
			}
			break;
		default:
			break;
		}

	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		RadioButton selectedButton = (RadioButton) group
				.findViewById(checkedId);
		long answerId = (Long) group.getTag();
		QuestionDBHelper.updateUserReply(answerId, selectedButton.getText()
				.toString());
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		boolean consuming = mGestureDetector.onTouchEvent(event);
		if (consuming == false && event.getAction() == MotionEvent.ACTION_UP) {
			v.performClick();
		}
		return consuming;
	}

	private void onSwipeLeft() {
		if (((QuizDetail) getActivity()).isLastPager() == false) {
			((QuizDetail) getActivity()).nextQuestion();
		}
	}

	private void onSwipeRight() {
		if (((QuizDetail) getActivity()).isFirstPager() == false) {
			((QuizDetail) getActivity()).backQuestion();
		}
	}
}
